package com.ldxx.common.intercepter;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.ldxx.common.annotation.PassToken;
import com.ldxx.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    BasicManageUserService basicManageUserService;

    @Autowired
    DrillCheckUserService drillCheckUserService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Content-Type", "text/html;charset=UTF-8");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        String appToken = httpServletRequest.getHeader("appToken");// 从 http 请求头中取出 token
        if (token == null) {
            token = httpServletRequest.getParameter("token");
        }
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        if (token == null) {
            token = appToken;
        }

        R r = new R();
        // 执行认证
        if (token == null) {
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write(JSON.toJSONString(r.error(10009, "未携带token,请重新登录")));
            return false;
        }
        // 获取 token 中的 user id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write(JSON.toJSONString(r.error(10009, "token异常,请重新登录")));
            return false;
        }
        BaseUser user;
        if (appToken != null && appToken != "") {
            user = drillCheckUserService.getById(userId);
        } else {
            user = basicManageUserService.getById(userId);
        }
        if (user == null) {
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write(JSON.toJSONString(r.error(10009, "用户不存在,请重新登录")));
            return false;
        }
        // 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            PrintWriter writer = httpServletResponse.getWriter();
            writer.write(JSON.toJSONString(r.error(10009, "token验证失败,请重新登录")));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}